3 * MediaWiki\Session entry point
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 namespace MediaWiki\Session
;
26 use Psr\Log\LoggerInterface
;
36 * This serves as the entry point to the MediaWiki session handling system.
41 final class SessionManager
implements SessionManagerInterface
{
42 /** @var SessionManager|null */
43 private static $instance = null;
45 /** @var Session|null */
46 private static $globalSession = null;
48 /** @var WebRequest|null */
49 private static $globalSessionRequest = null;
51 /** @var LoggerInterface */
57 /** @var BagOStuff|null */
60 /** @var BagOStuff|null */
63 /** @var SessionProvider[] */
64 private $sessionProviders = null;
67 private $varyCookies = null;
70 private $varyHeaders = null;
72 /** @var SessionBackend[] */
73 private $allSessionBackends = array();
75 /** @var SessionId[] */
76 private $allSessionIds = array();
79 private $preventUsers = array();
82 * Get the global SessionManager
83 * @return SessionManagerInterface
84 * (really a SessionManager, but this is to make IDEs less confused)
86 public static function singleton() {
87 if ( self
::$instance === null ) {
88 self
::$instance = new self();
90 return self
::$instance;
94 * Get the "global" session
96 * If PHP's session_id() has been set, returns that session. Otherwise
97 * returns the session for RequestContext::getMain()->getRequest().
101 public static function getGlobalSession() {
102 if ( !PHPSessionHandler
::isEnabled() ) {
108 $request = \RequestContext
::getMain()->getRequest();
110 !self
::$globalSession // No global session is set up yet
111 || self
::$globalSessionRequest !== $request // The global WebRequest changed
112 ||
$id !== '' && self
::$globalSession->getId() !== $id // Someone messed with session_id()
114 self
::$globalSessionRequest = $request;
116 // session_id() wasn't used, so fetch the Session from the WebRequest.
117 // We use $request->getSession() instead of $singleton->getSessionForRequest()
118 // because doing the latter would require a public
119 // "$request->getSessionId()" method that would confuse end
120 // users by returning SessionId|null where they'd expect it to
121 // be short for $request->getSession()->getId(), and would
122 // wind up being a duplicate of the code in
123 // $request->getSession() anyway.
124 self
::$globalSession = $request->getSession();
126 // Someone used session_id(), so we need to follow suit.
127 // Note this overwrites whatever session might already be
128 // associated with $request with the one for $id.
129 self
::$globalSession = self
::singleton()->getSessionById( $id, true, $request )
130 ?
: $request->getSession();
133 return self
::$globalSession;
137 * @param array $options
138 * - config: Config to fetch configuration from. Defaults to the default 'main' config.
139 * - logger: LoggerInterface to use for logging. Defaults to the 'session' channel.
140 * - store: BagOStuff to store session data in.
142 public function __construct( $options = array() ) {
143 if ( isset( $options['config'] ) ) {
144 $this->config
= $options['config'];
145 if ( !$this->config
instanceof Config
) {
146 throw new \
InvalidArgumentException(
147 '$options[\'config\'] must be an instance of Config'
151 $this->config
= \ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
154 if ( isset( $options['logger'] ) ) {
155 if ( !$options['logger'] instanceof LoggerInterface
) {
156 throw new \
InvalidArgumentException(
157 '$options[\'logger\'] must be an instance of LoggerInterface'
160 $this->setLogger( $options['logger'] );
162 $this->setLogger( \MediaWiki\Logger\LoggerFactory
::getInstance( 'session' ) );
165 $this->tempStore
= new \HashBagOStuff
;
166 if ( isset( $options['store'] ) ) {
167 if ( !$options['store'] instanceof BagOStuff
) {
168 throw new \
InvalidArgumentException(
169 '$options[\'store\'] must be an instance of BagOStuff'
172 $this->permStore
= $options['store'];
174 $this->permStore
= \ObjectCache
::getInstance( $this->config
->get( 'SessionCacheType' ) );
175 $this->permStore
->setLogger( $this->logger
);
178 register_shutdown_function( array( $this, 'shutdown' ) );
181 public function setLogger( LoggerInterface
$logger ) {
182 $this->logger
= $logger;
185 public function getSessionForRequest( WebRequest
$request ) {
186 $info = $this->getSessionInfoForRequest( $request );
189 $session = $this->getEmptySession( $request );
191 $session = $this->getSessionFromInfo( $info, $request );
196 public function getSessionById( $id, $create = false, WebRequest
$request = null ) {
197 if ( !self
::validateSessionId( $id ) ) {
198 throw new \
InvalidArgumentException( 'Invalid session ID' );
201 $request = new FauxRequest
;
206 // Test this here to provide a better log message for the common case
208 $key = wfMemcKey( 'MWSession', $id );
209 $existing = $this->tempStore
->get( $key );
210 if ( $existing === false ) {
211 $existing = $this->permStore
->get( $key );
212 if ( $existing !== false ) {
213 $this->tempStore
->set( $key, $existing );
216 if ( is_array( $existing ) ) {
217 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, array( 'id' => $id, 'idIsSafe' => true ) );
218 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
219 $session = $this->getSessionFromInfo( $info, $request );
223 if ( $create && $session === null ) {
226 $session = $this->getEmptySessionInternal( $request, $id );
227 } catch ( \Exception
$ex ) {
228 $this->logger
->error( __METHOD__
. ': failed to create empty session: ' .
237 public function getEmptySession( WebRequest
$request = null ) {
238 return $this->getEmptySessionInternal( $request );
242 * @see SessionManagerInterface::getEmptySession
243 * @param WebRequest|null $request
244 * @param string|null $id ID to force on the new session
247 private function getEmptySessionInternal( WebRequest
$request = null, $id = null ) {
248 if ( $id !== null ) {
249 if ( !self
::validateSessionId( $id ) ) {
250 throw new \
InvalidArgumentException( 'Invalid session ID' );
253 $key = wfMemcKey( 'MWSession', $id );
254 $existing = $this->tempStore
->get( $key );
255 if ( $existing === false ) {
256 $existing = $this->permStore
->get( $key );
257 if ( $existing !== false ) {
258 $this->tempStore
->set( $key, $existing );
261 if ( is_array( $existing ) ) {
262 throw new \
InvalidArgumentException( 'Session ID already exists' );
266 $request = new FauxRequest
;
270 foreach ( $this->getProviders() as $provider ) {
271 $info = $provider->newSessionInfo( $id );
275 if ( $info->getProvider() !== $provider ) {
276 throw new \
UnexpectedValueException(
277 "$provider returned an empty session info for a different provider: $info"
280 if ( $id !== null && $info->getId() !== $id ) {
281 throw new \
UnexpectedValueException(
282 "$provider returned empty session info with a wrong id: " .
283 $info->getId() . ' != ' . $id
286 if ( !$info->isIdSafe() ) {
287 throw new \
UnexpectedValueException(
288 "$provider returned empty session info with id flagged unsafe"
291 $compare = $infos ? SessionInfo
::compare( $infos[0], $info ) : -1;
292 if ( $compare > 0 ) {
295 if ( $compare === 0 ) {
298 $infos = array( $info );
302 // Make sure there's exactly one
303 if ( count( $infos ) > 1 ) {
304 throw new \
UnexpectedValueException(
305 'Multiple empty sessions tied for top priority: ' . join( ', ', $infos )
307 } elseif ( count( $infos ) < 1 ) {
308 throw new \
UnexpectedValueException( 'No provider could provide an empty session!' );
311 return $this->getSessionFromInfo( $infos[0], $request );
314 public function getVaryHeaders() {
315 if ( $this->varyHeaders
=== null ) {
317 foreach ( $this->getProviders() as $provider ) {
318 foreach ( $provider->getVaryHeaders() as $header => $options ) {
319 if ( !isset( $headers[$header] ) ) {
320 $headers[$header] = array();
322 if ( is_array( $options ) ) {
323 $headers[$header] = array_unique( array_merge( $headers[$header], $options ) );
327 $this->varyHeaders
= $headers;
329 return $this->varyHeaders
;
332 public function getVaryCookies() {
333 if ( $this->varyCookies
=== null ) {
335 foreach ( $this->getProviders() as $provider ) {
336 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
338 $this->varyCookies
= array_values( array_unique( $cookies ) );
340 return $this->varyCookies
;
344 * Validate a session ID
348 public static function validateSessionId( $id ) {
349 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
353 * @name Internal methods
358 * Auto-create the given user, if necessary
359 * @private Don't call this yourself. Let Setup.php do it for you at the right time.
360 * @note This more properly belongs in AuthManager, but we need it now.
361 * When AuthManager comes, this will be deprecated and will pass-through
362 * to the corresponding AuthManager method.
363 * @param User $user User to auto-create
364 * @return bool Success
366 public static function autoCreateUser( User
$user ) {
369 $logger = self
::singleton()->logger
;
371 // Much of this code is based on that in CentralAuth
373 // Try the local user from the slave DB
374 $localId = User
::idFromName( $user->getName() );
376 // Fetch the user ID from the master, so that we don't try to create the user
377 // when they already exist, due to replication lag
378 // @codeCoverageIgnoreStart
379 if ( !$localId && wfGetLB()->getReaderIndex() != 0 ) {
380 $localId = User
::idFromName( $user->getName(), User
::READ_LATEST
);
382 // @codeCoverageIgnoreEnd
385 // User exists after all.
386 $user->setId( $localId );
391 // Denied by AuthPlugin? But ignore AuthPlugin itself.
392 if ( get_class( $wgAuth ) !== 'AuthPlugin' && !$wgAuth->autoCreate() ) {
393 $logger->debug( __METHOD__
. ': denied by AuthPlugin' );
399 // Wiki is read-only?
400 if ( wfReadOnly() ) {
401 $logger->debug( __METHOD__
. ': denied by wfReadOnly()' );
407 $userName = $user->getName();
409 // Check the session, if we tried to create this user already there's
410 // no point in retrying.
411 $session = self
::getGlobalSession();
412 $reason = $session->get( 'MWSession::AutoCreateBlacklist' );
414 $logger->debug( __METHOD__
. ": blacklisted in session ($reason)" );
420 // Is the IP user able to create accounts?
422 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' )
423 ||
$anon->isBlockedFromCreateAccount()
425 // Blacklist the user to avoid repeated DB queries subsequently
426 $logger->debug( __METHOD__
. ': user is blocked from this wiki, blacklisting' );
427 $session->set( 'MWSession::AutoCreateBlacklist', 'blocked', 600 );
434 // Check for validity of username
435 if ( !User
::isCreatableName( $userName ) ) {
436 $logger->debug( __METHOD__
. ': Invalid username, blacklisting' );
437 $session->set( 'MWSession::AutoCreateBlacklist', 'invalid username', 600 );
444 // Give other extensions a chance to stop auto creation.
445 $user->loadDefaults( $userName );
447 if ( !\Hooks
::run( 'AbortAutoAccount', array( $user, &$abortMessage ) ) ) {
448 // In this case we have no way to return the message to the user,
449 // but we can log it.
450 $logger->debug( __METHOD__
. ": denied by hook: $abortMessage" );
451 $session->set( 'MWSession::AutoCreateBlacklist', "hook aborted: $abortMessage", 600 );
458 // Make sure the name has not been changed
459 if ( $user->getName() !== $userName ) {
462 throw new \
UnexpectedValueException(
463 'AbortAutoAccount hook tried to change the user name'
467 // Ignore warnings about master connections/writes...hard to avoid here
468 \Profiler
::instance()->getTransactionProfiler()->resetExpectations();
470 $cache = \ObjectCache
::getLocalClusterInstance();
471 $backoffKey = wfMemcKey( 'MWSession', 'autocreate-failed', md5( $userName ) );
472 if ( $cache->get( $backoffKey ) ) {
473 $logger->debug( __METHOD__
. ': denied by prior creation attempt failures' );
479 // Checks passed, create the user...
480 $from = isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : 'CLI';
481 $logger->info( __METHOD__
. ": creating new user ($userName) - from: $from" );
484 // Insert the user into the local DB master
485 $status = $user->addToDatabase();
486 if ( !$status->isOK() ) {
487 // @codeCoverageIgnoreStart
488 $logger->error( __METHOD__
. ': failed with message ' . $status->getWikiText() );
492 // @codeCoverageIgnoreEnd
494 } catch ( \Exception
$ex ) {
495 // @codeCoverageIgnoreStart
496 $logger->error( __METHOD__
. ': failed with exception ' . $ex->getMessage() );
497 // Do not keep throwing errors for a while
498 $cache->set( $backoffKey, 1, 600 );
499 // Bubble up error; which should normally trigger DB rollbacks
501 // @codeCoverageIgnoreEnd
504 # Notify hooks (e.g. Newuserlog)
505 \Hooks
::run( 'AuthPluginAutoCreate', array( $user ) );
506 \Hooks
::run( 'LocalUserCreated', array( $user, true ) );
508 # Notify AuthPlugin too
510 $wgAuth->initUser( $tmpUser, true );
511 if ( $tmpUser !== $user ) {
512 $logger->warning( __METHOD__
. ': ' .
513 get_class( $wgAuth ) . '::initUser() replaced the user object' );
516 $user->saveSettings();
519 \DeferredUpdates
::addUpdate( new \
SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
521 # Watch user's userpage and talk page
522 $user->addWatch( $user->getUserPage(), \WatchedItem
::IGNORE_USER_RIGHTS
);
528 * Prevent future sessions for the user
530 * The intention is that the named account will never again be usable for
531 * normal login (i.e. there is no way to undo the prevention of access).
533 * @private For use from \\User::newSystemUser only
534 * @param string $username
536 public function preventSessionsForUser( $username ) {
537 $this->preventUsers
[$username] = true;
539 // Reset the user's token to kill existing sessions
540 $user = User
::newFromName( $username );
541 if ( $user && $user->getToken( false ) ) {
543 $user->saveSettings();
546 // Instruct the session providers to kill any other sessions too.
547 foreach ( $this->getProviders() as $provider ) {
548 $provider->preventSessionsForUser( $username );
553 * Test if a user is prevented
554 * @private For use from SessionBackend only
555 * @param string $username
558 public function isUserSessionPrevented( $username ) {
559 return !empty( $this->preventUsers
[$username] );
563 * Get the available SessionProviders
564 * @return SessionProvider[]
566 protected function getProviders() {
567 if ( $this->sessionProviders
=== null ) {
568 $this->sessionProviders
= array();
569 foreach ( $this->config
->get( 'SessionProviders' ) as $spec ) {
570 $provider = \ObjectFactory
::getObjectFromSpec( $spec );
571 $provider->setLogger( $this->logger
);
572 $provider->setConfig( $this->config
);
573 $provider->setManager( $this );
574 if ( isset( $this->sessionProviders
[(string)$provider] ) ) {
575 throw new \
UnexpectedValueException( "Duplicate provider name \"$provider\"" );
577 $this->sessionProviders
[(string)$provider] = $provider;
580 return $this->sessionProviders
;
584 * Get a session provider by name
586 * Generally, this will only be used by internal implementation of some
587 * special session-providing mechanism. General purpose code, if it needs
588 * to access a SessionProvider at all, will use Session::getProvider().
590 * @param string $name
591 * @return SessionProvider|null
593 public function getProvider( $name ) {
594 $providers = $this->getProviders();
595 return isset( $providers[$name] ) ?
$providers[$name] : null;
599 * Save all active sessions on shutdown
600 * @private For internal use with register_shutdown_function()
602 public function shutdown() {
603 if ( $this->allSessionBackends
) {
604 $this->logger
->debug( 'Saving all sessions on shutdown' );
605 if ( session_id() !== '' ) {
606 // @codeCoverageIgnoreStart
607 session_write_close();
609 // @codeCoverageIgnoreEnd
610 foreach ( $this->allSessionBackends
as $backend ) {
611 $backend->save( true );
617 * Fetch the SessionInfo(s) for a request
618 * @param WebRequest $request
619 * @return SessionInfo|null
621 private function getSessionInfoForRequest( WebRequest
$request ) {
622 // Call all providers to fetch "the" session
624 foreach ( $this->getProviders() as $provider ) {
625 $info = $provider->provideSessionInfo( $request );
629 if ( $info->getProvider() !== $provider ) {
630 throw new \
UnexpectedValueException(
631 "$provider returned session info for a different provider: $info"
637 // Sort the SessionInfos. Then find the first one that can be
638 // successfully loaded, and then all the ones after it with the same
640 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
643 $info = array_pop( $infos );
644 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
647 $info = array_pop( $infos );
648 if ( SessionInfo
::compare( $retInfos[0], $info ) ) {
649 // We hit a lower priority, stop checking.
652 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
653 // This is going to error out below, but we want to
654 // provide a complete list.
661 if ( count( $retInfos ) > 1 ) {
662 $ex = new \
OverflowException(
663 'Multiple sessions for this request tied for top priority: ' . join( ', ', $retInfos )
665 $ex->sessionInfos
= $retInfos;
669 return $retInfos ?
$retInfos[0] : null;
673 * Load and verify the session info against the store
675 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
676 * @param WebRequest $request
677 * @return bool Whether the session info matches the stored data (if any)
679 private function loadSessionInfoFromStore( SessionInfo
&$info, WebRequest
$request ) {
680 $key = wfMemcKey( 'MWSession', $info->getId() );
681 $blob = $this->tempStore
->get( $key );
682 if ( $blob === false ) {
683 $blob = $this->permStore
->get( $key );
684 if ( $blob !== false ) {
685 $this->tempStore
->set( $key, $blob );
689 $newParams = array();
691 if ( $blob !== false ) {
692 // Sanity check: blob must be an array, if it's saved at all
693 if ( !is_array( $blob ) ) {
694 $this->logger
->warning( "Session $info: Bad data" );
695 $this->tempStore
->delete( $key );
696 $this->permStore
->delete( $key );
700 // Sanity check: blob has data and metadata arrays
701 if ( !isset( $blob['data'] ) ||
!is_array( $blob['data'] ) ||
702 !isset( $blob['metadata'] ) ||
!is_array( $blob['metadata'] )
704 $this->logger
->warning( "Session $info: Bad data structure" );
705 $this->tempStore
->delete( $key );
706 $this->permStore
->delete( $key );
710 $data = $blob['data'];
711 $metadata = $blob['metadata'];
713 // Sanity check: metadata must be an array and must contain certain
714 // keys, if it's saved at all
715 if ( !array_key_exists( 'userId', $metadata ) ||
716 !array_key_exists( 'userName', $metadata ) ||
717 !array_key_exists( 'userToken', $metadata ) ||
718 !array_key_exists( 'provider', $metadata )
720 $this->logger
->warning( "Session $info: Bad metadata" );
721 $this->tempStore
->delete( $key );
722 $this->permStore
->delete( $key );
726 // First, load the provider from metadata, or validate it against the metadata.
727 $provider = $info->getProvider();
728 if ( $provider === null ) {
729 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
731 $this->logger
->warning( "Session $info: Unknown provider, " . $metadata['provider'] );
732 $this->tempStore
->delete( $key );
733 $this->permStore
->delete( $key );
736 } elseif ( $metadata['provider'] !== (string)$provider ) {
737 $this->logger
->warning( "Session $info: Wrong provider, " .
738 $metadata['provider'] . ' !== ' . $provider );
742 // Load provider metadata from metadata, or validate it against the metadata
743 $providerMetadata = $info->getProviderMetadata();
744 if ( isset( $metadata['providerMetadata'] ) ) {
745 if ( $providerMetadata === null ) {
746 $newParams['metadata'] = $metadata['providerMetadata'];
749 $newProviderMetadata = $provider->mergeMetadata(
750 $metadata['providerMetadata'], $providerMetadata
752 if ( $newProviderMetadata !== $providerMetadata ) {
753 $newParams['metadata'] = $newProviderMetadata;
755 } catch ( \UnexpectedValueException
$ex ) {
756 $this->logger
->warning( "Session $info: Metadata merge failed: " . $ex->getMessage() );
762 // Next, load the user from metadata, or validate it against the metadata.
763 $userInfo = $info->getUserInfo();
765 // For loading, id is preferred to name.
767 if ( $metadata['userId'] ) {
768 $userInfo = UserInfo
::newFromId( $metadata['userId'] );
769 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
770 $userInfo = UserInfo
::newFromName( $metadata['userName'] );
772 $userInfo = UserInfo
::newAnonymous();
774 } catch ( \InvalidArgumentException
$ex ) {
775 $this->logger
->error( "Session $info: " . $ex->getMessage() );
778 $newParams['userInfo'] = $userInfo;
780 // User validation passes if user ID matches, or if there
781 // is no saved ID and the names match.
782 if ( $metadata['userId'] ) {
783 if ( $metadata['userId'] !== $userInfo->getId() ) {
784 $this->logger
->warning( "Session $info: User ID mismatch, " .
785 $metadata['userId'] . ' !== ' . $userInfo->getId() );
789 // If the user was renamed, probably best to fail here.
790 if ( $metadata['userName'] !== null &&
791 $userInfo->getName() !== $metadata['userName']
793 $this->logger
->warning( "Session $info: User ID matched but name didn't (rename?), " .
794 $metadata['userName'] . ' !== ' . $userInfo->getName() );
798 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
799 if ( $metadata['userName'] !== $userInfo->getName() ) {
800 $this->logger
->warning( "Session $info: User name mismatch, " .
801 $metadata['userName'] . ' !== ' . $userInfo->getName() );
804 } elseif ( !$userInfo->isAnon() ) {
805 // Metadata specifies an anonymous user, but the passed-in
806 // user isn't anonymous.
807 $this->logger
->warning(
808 "Session $info: Metadata has an anonymous user, " .
809 'but a non-anon user was provided'
815 // And if we have a token in the metadata, it must match the loaded/provided user.
816 if ( $metadata['userToken'] !== null &&
817 $userInfo->getToken() !== $metadata['userToken']
819 $this->logger
->warning( "Session $info: User token mismatch" );
822 if ( !$userInfo->isVerified() ) {
823 $newParams['userInfo'] = $userInfo->verified();
826 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
827 $newParams['remembered'] = true;
829 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
830 $newParams['forceHTTPS'] = true;
832 if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
833 $newParams['persisted'] = true;
836 if ( !$info->isIdSafe() ) {
837 $newParams['idIsSafe'] = true;
840 // No metadata, so we can't load the provider if one wasn't given.
841 if ( $info->getProvider() === null ) {
842 $this->logger
->warning( "Session $info: Null provider and no metadata" );
846 // If no user was provided and no metadata, it must be anon.
847 if ( !$info->getUserInfo() ) {
848 if ( $info->getProvider()->canChangeUser() ) {
849 $newParams['userInfo'] = UserInfo
::newAnonymous();
852 "Session $info: No user provided and provider cannot set user"
856 } elseif ( !$info->getUserInfo()->isVerified() ) {
857 $this->logger
->warning(
858 "Session $info: Unverified user provided and no metadata to auth it"
866 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
867 // The ID doesn't come from the user, so it should be safe
868 // (and if not, nothing we can do about it anyway)
869 $newParams['idIsSafe'] = true;
873 // Construct the replacement SessionInfo, if necessary
875 $newParams['copyFrom'] = $info;
876 $info = new SessionInfo( $info->getPriority(), $newParams );
879 // Allow the provider to check the loaded SessionInfo
880 $providerMetadata = $info->getProviderMetadata();
881 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
884 if ( $providerMetadata !== $info->getProviderMetadata() ) {
885 $info = new SessionInfo( $info->getPriority(), array(
886 'metadata' => $providerMetadata,
891 // Give hooks a chance to abort. Combined with the SessionMetadata
892 // hook, this can allow for tying a session to an IP address or the
894 $reason = 'Hook aborted';
897 array( &$reason, $info, $request, $metadata, $data )
899 $this->logger
->warning( "Session $info: $reason" );
907 * Create a session corresponding to the passed SessionInfo
908 * @private For use by a SessionProvider that needs to specially create its
910 * @param SessionInfo $info
911 * @param WebRequest $request
914 public function getSessionFromInfo( SessionInfo
$info, WebRequest
$request ) {
915 $id = $info->getId();
917 if ( !isset( $this->allSessionBackends
[$id] ) ) {
918 if ( !isset( $this->allSessionIds
[$id] ) ) {
919 $this->allSessionIds
[$id] = new SessionId( $id );
921 $backend = new SessionBackend(
922 $this->allSessionIds
[$id],
927 $this->config
->get( 'ObjectCacheSessionExpiry' )
929 $this->allSessionBackends
[$id] = $backend;
930 $delay = $backend->delaySave();
932 $backend = $this->allSessionBackends
[$id];
933 $delay = $backend->delaySave();
934 if ( $info->wasPersisted() ) {
937 if ( $info->wasRemembered() ) {
938 $backend->setRememberUser( true );
942 $request->setSessionId( $backend->getSessionId() );
943 $session = $backend->getSession( $request );
945 if ( !$info->isIdSafe() ) {
949 \ScopedCallback
::consume( $delay );
954 * Deregister a SessionBackend
955 * @private For use from \\MediaWiki\\Session\\SessionBackend only
956 * @param SessionBackend $backend
958 public function deregisterSessionBackend( SessionBackend
$backend ) {
959 $id = $backend->getId();
960 if ( !isset( $this->allSessionBackends
[$id] ) ||
!isset( $this->allSessionIds
[$id] ) ||
961 $this->allSessionBackends
[$id] !== $backend ||
962 $this->allSessionIds
[$id] !== $backend->getSessionId()
964 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
967 unset( $this->allSessionBackends
[$id] );
968 // Explicitly do not unset $this->allSessionIds[$id]
972 * Change a SessionBackend's ID
973 * @private For use from \\MediaWiki\\Session\\SessionBackend only
974 * @param SessionBackend $backend
976 public function changeBackendId( SessionBackend
$backend ) {
977 $sessionId = $backend->getSessionId();
978 $oldId = (string)$sessionId;
979 if ( !isset( $this->allSessionBackends
[$oldId] ) ||
!isset( $this->allSessionIds
[$oldId] ) ||
980 $this->allSessionBackends
[$oldId] !== $backend ||
981 $this->allSessionIds
[$oldId] !== $sessionId
983 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
986 $newId = $this->generateSessionId();
988 unset( $this->allSessionBackends
[$oldId], $this->allSessionIds
[$oldId] );
989 $sessionId->setId( $newId );
990 $this->allSessionBackends
[$newId] = $backend;
991 $this->allSessionIds
[$newId] = $sessionId;
995 * Generate a new random session ID
998 public function generateSessionId() {
1000 $id = wfBaseConvert( \MWCryptRand
::generateHex( 40 ), 16, 32, 32 );
1001 $key = wfMemcKey( 'MWSession', $id );
1002 } while ( isset( $this->allSessionIds
[$id] ) ||
1003 is_array( $this->tempStore
->get( $key ) ) ||
is_array( $this->permStore
->get( $key ) )
1009 * Call setters on a PHPSessionHandler
1010 * @private Use PhpSessionHandler::install()
1011 * @param PHPSessionHandler $handler
1013 public function setupPHPSessionHandler( PHPSessionHandler
$handler ) {
1014 $handler->setManager( $this, $this->permStore
, $this->logger
);
1018 * Reset the internal caching for unit testing
1020 public static function resetCache() {
1021 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
1022 // @codeCoverageIgnoreStart
1023 throw new MWException( __METHOD__
. ' may only be called from unit tests!' );
1024 // @codeCoverageIgnoreEnd
1027 self
::$globalSession = null;
1028 self
::$globalSessionRequest = null;